#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import asyncio
from fastapi import FastAPI
from fastapi.websockets import WebSocket


Q = asyncio.Queue(maxsize=100)
app = FastAPI(debug=True,
              title="WebSocket示例",
              version="0.0.1",
              description="描述",
              docs_url="/docs",
              redoc_url="/redocs")


@app.post("/msg")
async def revMsg(msg: dict) -> None:
    await Q.put(msg)
    return msg


@app.websocket("/ws")
async def msg(websocket: WebSocket) -> None:
    await websocket.accept()
    try:
        while True:
            # TODO: 消息发送失败将会丢失
            # TODO: 多客户端无法都收到消息
            msg = await Q.get()                                     # 获取消息
            await websocket.send_bytes(str(msg).encode("utf-8"))    # 发送到客户端

    except Exception as e:
        print(e)
        await websocket.close()
